//
//  VideoPlayerViewController.m
//  VideoPlayerExample
//
//  Created by Lin Eidan on 13-7-25.
//  Copyright (c) 2013年 taomee. All rights reserved.

//

#import "VideoPlayerViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <CoreImage/CoreImage.h>
#import <QuartzCore/QuartzCore.h>
#import "config.h"
#import "CustomLightControlView.h"
#import "VideoObj.h"
#import "Header.h"


typedef enum{
    DirectionLeft,
    DirectionRight,
    DirectionUp,
    DirectionDown,
    DirectionNo
} PanGesDirection;

#define AnimationDur                    0.3
#define DisappearDur                    8    //controlview自动消失的时间
#define HasLoadingOverDur               3.0   //加载的时间已经超过当前播放时间7s了，这样loading状态消失，越小loading按钮越早消失
#define FastDur                         30
#define FastOffset                      0     //最小10
#define UnLockViewDisappearDur          5    //解锁按钮自动消失的时间，
#define PlayFailedDur                   40   //超过这个时间，还没加载出来，就认定播放失败。

#define LargeModeScale                 (isiPhone5 ? 1.37 : 1.2) //双击放大后的比例。。
#define DisBetweenLabelAndSlider        0  //拖动条与label的距离

#define NumsOfColumn                (isPad ? 3 : 2)   //多少列
#define HeightOfEveryRow            (isPad ? 50 : 40)
#define WidthOfEverColumn           (isPad ? 80 : 58)


@interface VideoPlayerViewController ()

#pragma -mark Public
@property (strong, nonatomic) VideoObj *videoObj;
@property (assign, nonatomic) NSTimeInterval allDur;
@property (assign, nonatomic) NSTimeInterval startTime;
@property (strong, nonatomic) NSTimer *myTimer; //更新进度条
@property (assign, nonatomic) float nowWidth;
@property (assign, nonatomic) float nowHeight;

#pragma -mark View
@property (strong, nonatomic) UIView *tapView;
@property (strong, nonatomic) IBOutlet UIView   *stateView;
@property (strong, nonatomic) IBOutlet UIView   *stateBarBgViewIOS7;
@property (strong, nonatomic) IBOutlet UILabel  *titleLabel;

@property (strong, nonatomic) IBOutlet UIView   *controlView;
@property (strong, nonatomic) IBOutlet UIView   *controlBtnBgView;
@property (strong, nonatomic) IBOutlet UILabel  *hasPlayTimeLabel;
@property (strong, nonatomic) IBOutlet UILabel  *allDurLabel;
@property (strong, nonatomic) IBOutlet UIButton *playBtn;
@property (strong, nonatomic) IBOutlet UIButton *prevBtn;
@property (strong, nonatomic) IBOutlet UIButton *nextBtn;
@property (strong, nonatomic) IBOutlet UIButton *speedBtn;
@property (strong, nonatomic) IBOutlet UIButton *speedBackBtn;
@property (strong, nonatomic) SliderControlView *mySliderPageControl;
@property (strong, nonatomic) IBOutlet UIView   *actView;

#pragma -mark stateView controlView的显示
@property(strong, nonatomic) UITapGestureRecognizer *tapGes;
@property(strong, nonatomic) NSTimer *displayControlViewTimer;


#pragma -mark 手势快进退
@property (strong, nonatomic) UIPanGestureRecognizer *panGes;
@property (assign, nonatomic) PanGesDirection panGesDir;
@property (assign, nonatomic) float currentTimeTemp;
@property (strong, nonatomic) IBOutlet UIView *speedTipsView;
@property (strong, nonatomic) IBOutlet UILabel *speedHasToLabel;
@property (strong, nonatomic) IBOutlet UILabel *speedHasAddLabel;

#pragma -mark 手势调节音量,亮度。。
@property(strong, nonatomic) CustomVolumeControlView *customVolumeView;
@property(strong, nonatomic) CustomLightControlView *customLightView;
@property(assign, nonatomic) BOOL isLeft;  //左右
@property(assign, nonatomic) float defaultStartValue;
@property(assign, nonatomic) float endValueHasHandleOver;
@property(assign, nonatomic) float curYTemp;
@property(assign, nonatomic) float overValue;

#pragma -mark 锁屏
@property (strong, nonatomic) IBOutlet UIView *lockMaskView;
@property (strong, nonatomic) IBOutlet UIButton *unLockView;
@property (strong, nonatomic) NSTimer *lockTimer;
@property (assign, nonatomic) BOOL isLock;


#pragma -mark videoList
@property (strong, nonatomic) NSArray *videoListArray;
@property (assign, nonatomic) BOOL theVideoListArrayIsTrue;
@property (strong, nonatomic) CustomGridView *customGridView;
@property (assign, nonatomic) float goToDes;  //位置。。
@property (strong, nonatomic) NSMutableArray *dataArray;  //4列分别数组
@property (strong, nonatomic) IBOutlet UIView *videoListBgView;
@property (strong, nonatomic) IBOutlet UIButton *videoListBtn;

#pragma -mark Network
@property (strong, nonatomic) NSString* netType;

#pragma -mark 双击控制大小。
@property (strong, nonatomic) UITapGestureRecognizer *dbTapGes;
@property (assign, nonatomic) BOOL isInLargeMode;

#pragma -mark other
@property (strong, nonatomic) IBOutlet UIView *firstRunView;
@property (strong, nonatomic) NSTimer *playFailedTimer;  //无法播放的计时器，从开始进入页面，如果规定时间还没有加载出来，就算播放失败。
@property (strong, nonatomic) IBOutlet UIButton *collectOrNotBtn;
@property (strong, nonatomic) IBOutlet UIButton *downBtn;
@property (assign, nonatomic) float hasPlayedTime;
@property (assign, nonatomic) BOOL isGoBack;

@property (weak, nonatomic) IBOutlet UIView *sliderBgView;

@end


@implementation VideoPlayerViewController



-(id)initWithNibName:(NSString *)nibNameOrNil andObj:(VideoObj *)obj andListArray:(NSArray *)videoArray {
    self = [super initWithNibName:nibNameOrNil bundle:nil];
    if (self) {
        self.isInLargeMode = NO;
        self.videoObj = obj;
        self.theVideoListArrayIsTrue = NO;
        self.videoListArray = videoArray;
        self.isGoBack = NO;
    }
    return self;
    
}


- (void)viewDidLoad{
    [super viewDidLoad];
    [self startDrawView];
}

-(void)viewWillLayoutSubviews
{
    //NSLog(@"frame = %@",NSStringFromCGRect(self.view.frame));
    if(isiOS6)
    {
        self.view.frame = CGRectMake(0, 0, 320, isiPhone5 ? 568 : 480);
    }
}

-(void)startDrawView{
    //先保存，否则就会变了。
    if (!isPad) {
        self.view.width = isiPhone5 ? 568 : 480;
    }
    
    self.nowWidth = self.view.width;
    self.nowHeight = self.view.height;
    [self firstGoToPlay];
    
    self.actView.layer.cornerRadius=10;
    self.speedTipsView.layer.cornerRadius=10;
    self.sliderBgView.layer.cornerRadius = 1;
    self.sliderBgView.clipsToBounds = YES;
    if (isiOS7) {
        self.stateBarBgViewIOS7.hidden=NO;
    }else{
        self.stateBarBgViewIOS7.hidden=NO;
    }
    
    self.videoListBgView.left = self.nowWidth;
    self.speedTipsView.hidden=YES;
    self.downBtn.enabled = NO;
   
    //lock init
    self.lockMaskView.hidden=YES;
    self.isLock=NO;
    UITapGestureRecognizer *displayOrHideUnLockViewGes=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(displayOrHideUnLockView)];
    [self.lockMaskView addGestureRecognizer:displayOrHideUnLockViewGes];
    
    //tapView
    self.tapView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.nowWidth, self.nowHeight)];
    self.tapView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:self.tapView];
    [self.view sendSubviewToBack:self.tapView];
    
    //手势
    self.tapGes=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTheControlViewDisplayOrNot)];  //点击
    self.panGes=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(hanleCurrentTimeWithPanGes:)];  //左右上下滑
    self.dbTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTheMoviePlayerFrameAfterDoubleClicked)]; //双击
    self.dbTapGes.numberOfTapsRequired = 2;
    
    //slider
    self.sliderBgView.layer.cornerRadius = 2;
    self.mySliderPageControl=[[SliderControlView alloc] initWithFrame:CGRectMake(1,0,self.sliderBgView.width-2, self.sliderBgView.height) andMinValue:0 andLeftBackgroundImageName:@"Shape-4-copy.png" andRightBg:@"Shape-4.png" andSliderBtnImageName:@"speed.png"  andLeftCapWidth:5.5 andTopCapHight:4.5 andPopImageName:nil andPopViewMove:0 andSliderLabelDisplay:0];
    [self.sliderBgView addSubview:self.mySliderPageControl];
    self.mySliderPageControl.delegate = self;
    
    //volume light
    self.customVolumeView=[[CustomVolumeControlView alloc] initWithFrame:CGRectMake(0, 0, 150, 40) andDelegate:self];
    self.customLightView=[[CustomLightControlView alloc] initWithFrame:CGRectMake(0, 0,150, 40)];
    
    //videolist
    self.customGridView=[[CustomGridView alloc] initWithFrame:CGRectMake(0, 0, self.videoListBgView.width, self.videoListBgView.height)];
    self.customGridView.customGridViewdataSource=self;
    self.customGridView.customGridViewdelegate=self;
    [self.customGridView setGridViewLeft:isPad ? 1.5 : 2];
    [self.customGridView drawOtherViewBeforeGridView:nil andGridViewTop:isPad ? 5 : 0];
    [self.videoListBgView addSubview:self.customGridView];
    
    
    //player
    self.moviePlayer=[[MPMoviePlayerController alloc] init];
    self.moviePlayer.controlStyle = MPMovieControlStyleNone;
    [self.view addSubview:self.moviePlayer.view];
    [self.view sendSubviewToBack:self.moviePlayer.view];
    
    if (isPad) {
        self.videoListBgView.layer.cornerRadius = 5;
        self.videoListBgView.clipsToBounds = YES;
    }else{
        [Common putTheView:self.actView inHorizontalCenterOfParentView:self.view];
        [Common putTheView:self.speedTipsView inHorizontalCenterOfParentView:self.view];
        [Common putTheView:self.controlBtnBgView inHorizontalCenterOfParentView:self.controlView];
    }
    
    [self startGetPlayDetailDataWithCreateDownloadTypePlayListArray:YES];
    [self handleTheVideoList];
}

#pragma -mark 请求数据
-(void)startGetPlayDetailDataWithCreateDownloadTypePlayListArray:(BOOL) isNeedCreate{
    self.isGoBack = NO;
    self.titleLabel.text = self.videoObj.contentName;
    self.controlView.alpha=0;
    self.stateView.alpha = 1;
    self.actView.hidden = NO;
    self.videoListBgView.left=self.nowWidth;
    
    
    
    //是否已经在下载队列里。
    VideoObj *obj = [[DownloadVideoManager sharedInstance] getTheObjFromSuccessQueueWithContentId:self.videoObj.contentId andEpisodeId:self.videoObj.episodeId];
    
    if (obj) {  //local
        self.videoObj = [[kHandle sharedInstance] createANewObjWithOldObject:obj];
        NSLog(@"videoObj.id = %@",self.videoObj.episodeId);
        [self trueStartPlay];
        
    }else{  //inline
        
        self.videoObj.isInDownload = [[DownloadVideoManager sharedInstance] findTheEpisodeIsInSuccessQueueWithContentId:self.videoObj.contentId andEpisodeId:self.videoObj.episodeId andIsNeedToFindInDowningQueue:YES];
        
        if ([self.videoObj.episodeId isEqualToString:@"-1"]) {   //防止从下载变成无下载，然后又突然有网络，请求数据有误。。
            [self handleGetPlayDetailDataFailedWithText:NotifyNoNet];
            return;
        }
        
        NSString* url = [NSString stringWithFormat:@"%@getVideoUrl&pf=2&id=%@",API_BASE,self.videoObj.episodeId];
        [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
            if(isSuccess)
            {
                [self getPlayUrlSuccess:responseObj];
            }
            else{
                [self getPlayUrlError];
            }
        }];
    }
}

#pragma mark - 获取播放地址
-(void)getPlayUrlSuccess:(id)responseObj
{
    NSDictionary* dic = (NSDictionary*)responseObj;
    NSLog(@"dic = %@",dic);
    self.videoObj.playURL = [[dic objectForKey:@"url"] objectForKey:@"url"];
    [self trueStartPlay];
}

-(void)getPlayUrlError
{
    [self handleGetPlayDetailDataFailedWithText:NotifyNoNet];
}



-(void)trueStartPlay{
    if (IsNull(self.videoObj.playURL)) {
        [self handleGetPlayDetailDataFailedWithText:TipsFailedTextVideo];
        return;
    }
   
    [self handlePrevAndNextBtnIsEnable];
    self.videoObj.hasPlayDur = [UserDataBasic getHasPlayedDurFromHistoryWith:self.videoObj];
   
    self.startTime = self.videoObj.hasPlayDur;
    self.allDur = 0;
    
    //player
    if (self.moviePlayer == nil) {
        return;
    }
    
    [self.moviePlayer stop];
    NSURL *videoURL=[NSURL URLWithString:self.videoObj.playURL];
    self.moviePlayer.contentURL = videoURL;
    self.isInLargeMode = !self.isInLargeMode;
    [self handleTheMoviePlayerFrameWithAnimation:NO];
    [self.moviePlayer play];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoPlayingStateChange) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];  //播放状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoHasFinishPlay:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];  //播放完成。。
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoLoadStateChange) name:MPMoviePlayerLoadStateDidChangeNotification object:nil];  //加载状态
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWhenAppTerminate) name:UIApplicationWillTerminateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWhenAppDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWhenAppDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    if (self.isLock) {
       
        [self handleTheStartBarAndStateViewDisplayWithNoAnimation:NO];  //锁屏就关掉吧。
    }
    
    [self displayThePreparePlayTipsView];
    
    
}

#pragma mark - 错误处理
-(void)handleGetPlayDetailDataFailedWithText:(NSString *)text{
    [PopTips tips:self.view Msg:text];
    [self performSelector:@selector(goBack:) withObject:nil afterDelay:1];
}


//准备播放 的提示文字
-(void)displayThePreparePlayTipsView{
    if (!self.videoObj.isComplete) {  //不是下载的才提示。。
        [[kHandle sharedInstance] normalPageHandleInThe3GInView:self.view];
    }
    
    if (self.startTime > 0) {
        [PopTips tips:self.view Msg:[NSString stringWithFormat:@"上次播放到：%@",[Common handleTheTime:self.startTime]]];
    }
}


#pragma -mark background
-(void)handleWhenAppTerminate{
    [self handleTheHistoryAndCollectWithHasPlayed:self.moviePlayer.currentPlaybackTime];
}

-(void)handleWhenAppDidEnterBackground{
    [self handleTheHistoryAndCollectWithHasPlayed:self.moviePlayer.currentPlaybackTime];
}

-(void)handleWhenAppDidBecomeActive{
    if (self.moviePlayer.playbackState == MPMoviePlaybackStatePaused) {
        [self controlTheVideoPlay:nil];
    }
    BOOL hidden = [UIApplication sharedApplication].statusBarHidden;
    if (hidden && !isiOS7) { //如果是ios6 且 从后台到前台状态栏是隐藏的话，那么需要特殊处理，否则退出播放器，会有20像素的抖动，处理就是先让状态栏出来，然后0.4s后再隐藏。
        //[kApp handleTheStartBarWhenStartPlayDisplay:YES];
        [self performSelector:@selector(delayToHiddeTheStateBarWhenNeed) withObject:nil afterDelay:0.4];
    }
}

-(void)delayToHiddeTheStateBarWhenNeed{
    //[kApp handleTheStartBarWhenStartPlayDisplay:NO];
}

#pragma -mark player handle

-(IBAction)controlTheVideoPlay:(id)sender{
    if (self.moviePlayer.playbackState == MPMoviePlaybackStatePaused ) {
        [self.moviePlayer play];
    }else if (self.moviePlayer.playbackState == MPMoviePlaybackStatePlaying){
        [self.moviePlayer pause];
    }
}
//加载状态，可以播放
-(void)videoLoadStateChange{
    if (self.moviePlayer.loadState ) {
        if (self.moviePlayer.duration > 0  && self.allDur == 0) {
            
            self.allDur=self.moviePlayer.duration;
            self.allDurLabel.text=[Common handleTheTime:self.allDur];
            [self moviePlaySeekToValue:self.startTime andHandleFlag:YES];
            [self.playFailedTimer invalidate];
            [self updateSliderTimeProccess];
            self.myTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateSliderTimeProccess) userInfo:nil repeats:YES];
            
            self.actView.hidden=YES;
            [self.mySliderPageControl SliderControlSetUpMaxValue:self.allDur];
            
            if (!self.isLock) {  //如果锁屏了，就不出现stateView,不锁屏才出现。
                //NSLog(@"kkkkkkkkkkkkkkkkkkk");
                [self handleTheStartBarAndStateViewDisplayWithNoAnimation:YES];
            }
            
            //手势
            [self.tapView addGestureRecognizer:self.tapGes];
            [self.tapView addGestureRecognizer:self.dbTapGes];
            [self.tapView addGestureRecognizer:self.panGes];
            
        }
    }
   
}


//跳到指定时间
-(void)moviePlaySeekToValue:(float)toValue andHandleFlag:(BOOL)flag{
    if (flag) {
        toValue=(toValue > self.allDur-FastOffset) ? (self.allDur-FastOffset) : (toValue);
    }
    [self.moviePlayer play];
    self.hasPlayTimeLabel.text=[Common handleTheTime:toValue];
    self.moviePlayer.currentPlaybackTime=toValue;
}

//拖动进度条,先暂停一下。。就会去调用 状态通知，控制view就不会消失。
-(void)SliderControlContinueToValue:(float)toValue{
    
    [self closeVideoListView];
    [self.moviePlayer pause];
    self.hasPlayTimeLabel.text=[Common handleTheTime:toValue];
    self.moviePlayer.currentPlaybackTime=toValue;
}

//进度条按钮抬起，，开始播放。。
-(void)SliderControlHasToValue:(float)toValue{
    [self moviePlaySeekToValue:toValue andHandleFlag:YES];
}

//快进，快退处理
-(IBAction)playFastForwardOrBackWard:(id)sender{
  
    UIButton *btn=(UIButton *)sender;
    NSTimeInterval toTime;
    if (btn == self.speedBtn) {
        if (self.moviePlayer.currentPlaybackTime + FastDur >= self.allDur-FastOffset) {
            toTime=(self.moviePlayer.currentPlaybackTime > self.allDur-FastOffset) ? (self.moviePlayer.currentPlaybackTime) : (self.allDur-FastOffset);
        }else{
            toTime=self.moviePlayer.currentPlaybackTime+FastDur;
        }
    }else{
        if (self.moviePlayer.currentPlaybackTime - FastDur <= 0) {
            toTime=0;
        }else{
            toTime=self.moviePlayer.currentPlaybackTime-FastDur;
        }
    }
    if (toTime == 0 && self.moviePlayer.currentPlaybackTime < 1) {  //防止在开头，重复点击回退键。
        return;
    }
    [self moviePlaySeekToValue:toTime andHandleFlag:NO];
    
}

//更新进度条
-(void)updateSliderTimeProccess{
    float dur = 0;
    if (self.moviePlayer.loadState) {
        dur=self.moviePlayer.playableDuration-self.moviePlayer.currentPlaybackTime;
    }
    
    if (dur <=0) {
        dur = 0;
    }
    
    if (self.videoObj.isComplete) {
        self.actView.hidden = YES;
    }else{
        if ((dur < HasLoadingOverDur && self.allDur - self.moviePlayer.currentPlaybackTime > HasLoadingOverDur) || dur == 0) { //防止播放到最后，也出现loading
            self.actView.hidden=NO;
        }else{
            self.actView.hidden=YES;
        }
    }
    
    
    self.hasPlayTimeLabel.text=[Common handleTheTime:(int)self.moviePlayer.currentPlaybackTime];
    [self.mySliderPageControl SliderControlSetUpToValue:(int)self.moviePlayer.currentPlaybackTime];
    
}

//播放状态改变的通知
-(void)videoPlayingStateChange{
    if (self.moviePlayer.playbackState == MPMoviePlaybackStatePaused || self.moviePlayer.playbackState == MPMoviePlaybackStateStopped) {  //暂停状态
        self.playBtn.selected=NO;
        [self.displayControlViewTimer invalidate];
    }else if (self.moviePlayer.playbackState == MPMoviePlaybackStatePlaying ){
        self.playBtn.selected=YES;
        [self handleTheDisplayControlViewTimer];
    }
}

//电影播放完后的处理
-(void)videoHasFinishPlay:(NSNotification *)paramNotification{
    
    NSNumber *reason = [paramNotification.userInfo valueForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
    
    if (reason != nil){
        NSInteger reasonAsInteger = [reason integerValue];
        
        switch (reasonAsInteger){
            case MPMovieFinishReasonPlaybackEnded:{   /* The movie ended normally */
                
                if (self.moviePlayer.loadState) {
                    [self handleTheNextAndPrevPlayableWithFlag:1];  //下一集
                }else{
                    //点击退出的时候会调用,点击电源键，再进来也会调用
                    if (!self.isGoBack && self.videoObj.isComplete) { //播放本地的，然后关闭屏幕，播放器失效,所以不是用户主动退出的就要重播。服务器的重启，下面会调用的，这边不用。
                        [self performSelector:@selector(delayToPlayAgainWhenError) withObject:nil afterDelay:0.3];
                    }
                }
                
                break;
            }
            case MPMovieFinishReasonPlaybackError:{  /* An error happened and the movie ended */
                if (self.videoObj.isComplete) {  //下载的视频如果播放有误，一般是本地服务器当掉了，重启一下,重新播放
                    [[kHandle sharedInstance] startLocalServer];
                    [self performSelector:@selector(delayToPlayAgainWhenError) withObject:nil afterDelay:0.3];
                }else{
                    [self handleGetPlayDetailDataFailedWithText:TipsFailedTextVideo];  //如果不是下载而是在线，只能是片子不给力拉。
                }
                
                break;
            }
            case MPMovieFinishReasonUserExited:{
                
                /* The user exited the player */
                break;
            }
                
        }
    }
    
}


-(void)delayToPlayAgainWhenError{
    [self handleWhenGoBackWithEpisodeId:self.videoObj.episodeId andIsNeedToHandleTheVideoList:YES];
}

#pragma -mark goBack
-(IBAction)goBack:(id)sender{
    [[AFGetData sharedInstance] removeAllGetAndPostRequest];
   
    //直接退出的才是nil，这样防止请求到网络的时候，又继续播放。
    self.hasPlayedTime = self.moviePlayer.currentPlaybackTime;
    [self.moviePlayer stop];
    self.moviePlayer = nil;
    

    [self handleWhenGoBackWithEpisodeId:@"-1" andIsNeedToHandleTheVideoList:NO];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)handleWhenGoBackWithEpisodeId:(NSString *)episodeId andIsNeedToHandleTheVideoList:(BOOL)isNeed{
     self.isGoBack = YES;
    //上下集播放，存历史记录，不nil，还要用。
    if (self.moviePlayer) {
        self.hasPlayedTime = self.moviePlayer.currentPlaybackTime;
        [self.moviePlayer stop];
    }
    
    [self closeVideoListView];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [self.tapView removeGestureRecognizer:self.panGes];
    [self.tapView removeGestureRecognizer:self.dbTapGes];
    [self.tapView removeGestureRecognizer:self.tapGes];
    
    [self.myTimer invalidate];
    [self.displayControlViewTimer invalidate];
    
    //自动退出也要让状态栏可见。。
    //[kApp handleTheStartBarWhenStartPlayDisplay:YES];
    
    //history
    [self handleTheHistoryAndCollectWithHasPlayed:self.hasPlayedTime];
    
  
    if (![episodeId isEqualToString:@"-1"]) {
        
        [self startGetPlayDetailDataWithCreateDownloadTypePlayListArray:NO];
        if (isNeed) {
            [self delayHandleTheVideoListGoToRightPos];
        }
        
    }
}

//历史记录和收藏相关处理。
-(void)handleTheHistoryAndCollectWithHasPlayed:(float) hasPlayed{

    if (hasPlayed > 0) {
        self.videoObj.hasPlayDur = hasPlayed;
        [UserDataBasic addVideoObjToHistory:self.videoObj];
       }
}

#pragma -mark Network
//监测到变成3G网络的处理。
-(void)handleWhenChangeTo3G{
    if (!self.videoObj.isComplete) {
        if (self.moviePlayer.playbackState == MPMoviePlaybackStatePlaying){
            [self controlTheVideoPlay:nil];
        }
        [PopTips tips:self.view Msg:TipsChangeTo3GText];
    }
}

//监测到没有网络的时候，自动退出。。
-(void)noNetWorkToGoBackWithText:(NSString *)text{
    if (!self.videoObj.isComplete) {   //非下载模式，才退出。。
        [self handleGetPlayDetailDataFailedWithText:text];
    }
}

#pragma -mark 列表，选集
-(void)closeVideoListView{
    if (self.videoListBtn.selected) {
        [self openOrCloseVideoList:self.videoListBtn];
    }
}
- (IBAction)openOrCloseVideoList:(id)sender {
    
    UIButton *btn=(UIButton *)sender;
    if (btn.selected) {  //点击后，list消失，重新计时
        btn.selected=NO;
        [UIView animateWithDuration:AnimationDur animations:^{
            self.videoListBgView.left=self.nowWidth;
        }];
        
        [self handleTheDisplayControlViewTimer];
        
    }else{  //点击后，list display，计时失效
        
        [self videoListGoToRightPosWithReloadDataOrNot:NO];

        
        btn.selected=YES;
        [UIView animateWithDuration:AnimationDur animations:^{
            self.videoListBgView.left=self.nowWidth-self.videoListBgView.width;
        }];
        
        [self.displayControlViewTimer invalidate];
        
    }
}

//播放下一，上一。
-(IBAction)playNextOrPre:(id)sender{
    
    
    //还要实现知道是否有上下集，改变按钮状态
    UIButton *btn=(UIButton *)sender;
    int flag=1;
    if (btn == self.prevBtn) {
        flag = -1;
    }
    [self handleTheNextAndPrevPlayableWithFlag:flag];
    
}

//找到可播放的剧集，因为下一集可能是没有链接的。。。
-(void)handleTheNextAndPrevPlayableWithFlag:(int )flag{
    int index= self.videoObj.currentPlayIndex;
    index=index+flag;
    
    BOOL isCanPlay=NO;
    if (flag == 1 ) {
        for (int i= index; i< self.videoListArray.count; i++) {
//            NSDictionary *cur=[self.videoListArray objectAtIndex:i];
            //BOOL isHave=[[cur objectForKey:HttpEveryEpisodeHave] intValue];
            BOOL isHave = YES;
            if (isHave) {
                index=i;
                isCanPlay=YES;
                break;
            }
        }
    }else{
        for (int i= index; i>= 0; i--) {
//            NSDictionary *cur=[self.videoListArray objectAtIndex:i];
            //BOOL isHave=[[cur objectForKey:HttpEveryEpisodeHave] intValue];
            BOOL isHave = YES;
            if (isHave) {
                index=i;
                isCanPlay=YES;
                break;
            }
        }
        
    }
    
    if (isCanPlay) {
//        [self handleWhenGoBackWithPlayIndex:index andIsNeedToHandleTheVideoList:YES];
    }else{
        [self goBack:nil];
    }
    
}

-(void)handleTheVideoList{
    
    if (self.videoListArray.count <=1 || IsNull(self.videoListArray)) {
        self.videoListBtn.enabled=NO;
    }else{
        self.videoListBtn.enabled=YES;
        
        self.dataArray=[[NSMutableArray alloc] initWithCapacity:NumsOfColumn];
        for (int i=0; i<NumsOfColumn; i++) {
            NSMutableArray *columnArray=[[NSMutableArray alloc] init];
            [self.dataArray addObject:columnArray];
        }
        
        //获得数据后，依次放进对应的数组
        for (int i=0; i<self.videoListArray.count; i++) {
            [[self.dataArray objectAtIndex:i%NumsOfColumn] addObject:[self.videoListArray objectAtIndex:i]];
        }
        [self.customGridView reloadData];
        [self videoListGoToRightPosWithReloadDataOrNot:YES];
    }
    
    
    //处理上下按钮的可用性。。
    [self handlePrevAndNextBtnIsEnable];
    
}

//处理上一，下一按钮的可用性
-(void)handlePrevAndNextBtnIsEnable{
    
    //下载按钮
    if (!self.videoObj.isInDownload && self.theVideoListArrayIsTrue && !IsNull(self.videoListArray)) {
        self.downBtn.enabled = YES;
    }else{
        self.downBtn.enabled = NO;
    }
    
    if (self.videoListArray.count == 0 || self.videoListArray == nil) {
        self.prevBtn.enabled=NO;
        self.nextBtn.enabled=NO;
    }else{
        if (self.videoListArray.count - 1 > self.videoObj.currentPlayIndex) {
            self.nextBtn.enabled=YES;
        }else{
            self.nextBtn.enabled=NO;
        }
        
        if (self.videoObj.currentPlayIndex > 0) {
            self.prevBtn.enabled=YES;
        }else{
            self.prevBtn.enabled=NO;
        }
    }
}

-(void)delayHandleTheVideoListGoToRightPos{
    [self videoListGoToRightPosWithReloadDataOrNot:YES];
}

-(void)videoListGoToRightPosWithReloadDataOrNot:(BOOL) isNeedToReloadData{
    self.goToDes=HeightOfEveryRow*(int)(self.videoObj.currentPlayIndex/NumsOfColumn);
    
    if (self.goToDes + self.customGridView.height > self.customGridView.contentHeight) {
        self.goToDes=self.customGridView.contentHeight-self.customGridView.height;
    }
    
    if(self.goToDes < 0){
        self.goToDes = 0;
    }
    
    self.customGridView.contentOffsetTop=self.goToDes;
    if (isNeedToReloadData) {
        [self.customGridView reloadData];
    }else{
        [self.customGridView onScroll];
    }
}

#pragma -mark stateView controlView的显示

//控制状态栏和状态view的可见性，不带动画。
-(void)handleTheStartBarAndStateViewDisplayWithNoAnimation:(BOOL)isDisplay{
//    [kApp handleTheStartBarWhenStartPlayDisplay:isDisplay];
    [self handleAlpha:isDisplay];
}

-(void)handleTheDisplayControlViewTimer{
    if (self.controlView.alpha == 1) {
        [self.displayControlViewTimer invalidate];
        self.displayControlViewTimer=[NSTimer scheduledTimerWithTimeInterval:DisappearDur target:self selector:@selector(handleTheControlViewDisplayOrNot) userInfo:nil repeats:YES];
    }
}

//控制controlView的显示与隐藏
-(void)handleTheControlViewDisplayOrNot{
    
    if (self.stateView.alpha == 1 ) {  //点击关闭
        
        [self closeVideoListView];
        
        [UIView animateWithDuration:AnimationDur animations:^{
            [self handleAlpha:0];
            [Common handleTheStatusBarDislay:NO];
        }];
        [self handleTheStateBarAnimationDur:AnimationDur andDisplay:NO];
        
    }else{  //点击打开
        [UIView animateWithDuration:AnimationDur animations:^{
            [self handleAlpha:1];
            [Common handleTheStatusBarDislay:YES];
        }];
        [self handleTheStateBarAnimationDur:AnimationDur andDisplay:YES];
    }
}

-(void)handleAlpha:(float)alpha{
    self.stateView.alpha=alpha;
    if (alpha == 0) {
        self.controlView.alpha=alpha;
        [self.displayControlViewTimer invalidate];
    }else if (alpha == 1){
        if (self.moviePlayer.duration > 0 && self.moviePlayer.loadState ) {
            self.controlView.alpha=alpha;
        }else{
            self.controlView.alpha=0;
        }
        [self handleTheDisplayControlViewTimer];
        
    }
}

#pragma -mark 双击改变尺寸
-(void)handleTheMoviePlayerFrameAfterDoubleClicked{
    [self handleTheMoviePlayerFrameWithAnimation:YES];
}

-(void)handleTheMoviePlayerFrameWithAnimation:(BOOL) isAnimation{
    float scale = 1;
    if (self.isInLargeMode) {  //双击后，变正常。
        
    }else{  //双击后，变大。
        scale = LargeModeScale;
    }
    self.isInLargeMode = !self.isInLargeMode;
    
    float animationDur = 0.0;
    if (isAnimation) {
        animationDur = 0.3;
    }
    [UIView animateWithDuration:animationDur animations:^{
        self.moviePlayer.view.frame=CGRectMake((self.nowWidth-self.nowWidth*scale)/2, (self.nowHeight-self.nowHeight*scale)/2, self.nowWidth*scale, self.nowHeight*scale);
    }];
    
}

#pragma -mark collect
-(void)checkIsInCollect{
    if (self.videoListArray.count == 0 || self.theVideoListArrayIsTrue == NO) {
        self.collectOrNotBtn.enabled=NO;
        return;
    }else{
        self.collectOrNotBtn.enabled = YES;
    }
}

- (IBAction)addOrRemoveFromCollect:(id)sender {
    
}

//下载
- (IBAction)downThisEpisode:(id)sender {
    

}

#pragma -mark 音量，快进
-(void)hanleCurrentTimeWithPanGes:(UIPanGestureRecognizer *)gestureRecognizer{
    
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {  //开始的时候，判断方向
        CGPoint point=[gestureRecognizer velocityInView:self.tapView];
        
        float curX=point.x;
        float curY=point.y;
        
        if (fabsf(curX)  >=  fabsf(curY)  ) {  //x的绝对值大于y，就是横滑动。
            if (curX > 0) {
                self.panGesDir = DirectionRight;
            }else{
                self.panGesDir = DirectionLeft;
            }
        }else{
            if (curY > 0) {
                self.panGesDir = DirectionDown;
            }else{
                self.panGesDir = DirectionUp;
            }
        }
        
        //横滑
        self.currentTimeTemp=self.moviePlayer.currentPlaybackTime;
        
        if (self.panGesDir == DirectionLeft || self.panGesDir == DirectionRight) {
            self.speedHasToLabel.text=[Common handleTheTime:self.currentTimeTemp];
            self.speedHasAddLabel.text=[NSString stringWithFormat:@"[%@]",[Common handleTheTime:0]];
            self.speedTipsView.hidden=NO;
        }
        
        //竖滑
        CGPoint locationPoint=[gestureRecognizer locationInView:self.tapView];
        if (locationPoint.x < self.tapView.width/2) {
            self.isLeft=YES;
        }else{
            self.isLeft=NO;
        }
        
        if (!self.isLeft) {  //左边亮度，右边声音。。
            
            
            self.defaultStartValue=[self.customVolumeView customVolumeViewGetValue];
        }else{
            
           
            self.defaultStartValue=[self.customLightView customLightControlViewGetValue];
        }
        
        self.endValueHasHandleOver=self.defaultStartValue;
        self.curYTemp=curY;
        self.overValue=0;
        
        
        if ((self.panGesDir == DirectionUp || self.panGesDir == DirectionDown) && self.isLeft) {
//            [self displayLightView];
        }
        
    }
    
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged){
        CGPoint point=[gestureRecognizer translationInView:self.tapView];
        float curX=point.x;
        float curY=point.y;
        
        //只有在开始的时候方向正确，且在范围内，在左右走。
        if (self.panGesDir == DirectionLeft || self.panGesDir == DirectionRight) {
            
            float offsetPad = 1;   //如果是ipad，再不灵敏一点。。
            if (isPad) {
                offsetPad = 1.3;
            }
            
            float tureAddTime;
            if (self.allDur > 3600) {
                tureAddTime=curX/offsetPad;
            }else if(self.allDur <= 3600 && self.allDur > 1800){
                tureAddTime=curX/2/offsetPad;
            }else{
                tureAddTime=curX/4/offsetPad;
            }
            
            float toValue=self.currentTimeTemp+tureAddTime;
            toValue=(toValue > self.allDur-FastOffset) ? (self.allDur-FastOffset) : (toValue);
            toValue=(toValue > 0) ? (toValue) : 0;
            
            
            tureAddTime=toValue-self.currentTimeTemp;
            
            
            if (tureAddTime > 0) {
                self.speedHasAddLabel.text=[NSString stringWithFormat:@"[+%@]",[Common handleTheTime:tureAddTime]];
            }else{
                self.speedHasAddLabel.text=[NSString stringWithFormat:@"[-%@]",[Common handleTheTime:-tureAddTime]];
            }
            
            self.speedHasToLabel.text= [Common handleTheTime:toValue];
            
            [self.mySliderPageControl SliderControlSetUpToValue:(int)toValue];
            [self SliderControlContinueToValue:toValue];
            
        }else if (self.panGesDir == DirectionUp || self.panGesDir == DirectionDown){
            
            float offsetPad = 250;   //如果是ipad，再不灵敏一点。。
            if (isPad) {
                offsetPad = 300;
            }
            
            float overTemp=(float)self.defaultStartValue-curY/offsetPad;   //灵敏度，，700最大，比较不灵敏，500最小，比较灵敏。
            if (curY < self.curYTemp) {  //向上走
                
                self.curYTemp=curY;
                if (self.endValueHasHandleOver<1) {
                    self.endValueHasHandleOver=overTemp-self.overValue;
                }else{
                    self.overValue=overTemp-self.endValueHasHandleOver;  //超过了，纪录超过的，下次一并减去。。
                }
                
            }else{   //向下走
                
                self.curYTemp=curY;
                if (self.endValueHasHandleOver >0) {
                    self.endValueHasHandleOver=overTemp-self.overValue;
                }else{
                    self.overValue=overTemp-self.endValueHasHandleOver;
                }
                
            }
            
            if (self.endValueHasHandleOver > 1) {
                self.endValueHasHandleOver=1;
            }else if (self.endValueHasHandleOver < 0){
                self.endValueHasHandleOver=0;
            }
            
            if (!self.isLeft) {
                [self.customVolumeView customVolumeViewSetValue:self.endValueHasHandleOver];
            }else{
                [self.customLightView customLightControlViewSetValue:self.endValueHasHandleOver];
            }
        }
    }
    
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        if (self.panGesDir == DirectionLeft || self.panGesDir == DirectionRight) {
            [self.moviePlayer play];
            self.speedTipsView.hidden=YES;
        }
        
        if ((self.panGesDir == DirectionUp || self.panGesDir == DirectionDown) && self.isLeft) {
//            [self closeLightView];
        }
        
    }
}

#pragma -mark 锁屏
//手势控制解锁按钮的出现。。
-(void)displayOrHideUnLockView{
    [self handleTheLockTimerWithFlag:YES];
}

//真正处理。。
-(void)handleTheLockTimerWithFlag:(BOOL)flag{
    if (self.unLockView.hidden && flag) {
        self.unLockView.hidden=NO;
        self.lockTimer=[NSTimer scheduledTimerWithTimeInterval:UnLockViewDisappearDur target:self selector:@selector(handleTheLockTimerWithFlag:) userInfo:NO repeats:NO];
    }else if(self.unLockView.hidden == NO ){
        self.unLockView.hidden=YES;
        [self.lockTimer invalidate];
    }
}

//解锁
-(IBAction)unLockScreen:(id)sender {
    self.lockMaskView.hidden=YES;
    self.isLock=NO;
    [self.view sendSubviewToBack:self.lockMaskView];
    [self handleTheControlViewDisplayOrNot];
    [self.lockTimer invalidate];
}

//锁屏
- (IBAction)lockScreen:(id)sender {
   
    self.lockMaskView.hidden=NO;
    self.isLock=YES;
    [self.view bringSubviewToFront:self.lockMaskView];
    [self handleTheControlViewDisplayOrNot];
    self.lockTimer=[NSTimer scheduledTimerWithTimeInterval:UnLockViewDisappearDur target:self selector:@selector(handleTheLockTimerWithFlag:) userInfo:NO repeats:NO];
}
#pragma mark - 全屏
- (IBAction)fillScreenClick:(id)sender {
    [self handleTheMoviePlayerFrameAfterDoubleClicked];
}

#pragma -mark 生成剧集列表
//有多少列
-(NSInteger)numberOfColumnsInCustomGridView:(CustomGridView *)customGridView{
    return NumsOfColumn;
    
}
//每一列有多少个cell
-(NSInteger)customGridView:(CustomGridView *)customGridView numberOfRowsInColumn:(NSInteger)column{
    return [[self.dataArray objectAtIndex:column] count];
}
//每一列的宽度
-(CGFloat)customGridView:(CustomGridView *)customGridView widthOfColumn:(NSInteger)column{
    return WidthOfEverColumn;
}

//每一个cell的高度
-(CGFloat)customGridView:(CustomGridView *)customGridView heightForCellsAtIndexPath:(CustomIndexPath *)indexPath{
    return HeightOfEveryRow;
}

-(CGFloat)customGridView:(CustomGridView *)customGridView topSpaceForCellsAtIndexPath:(CustomIndexPath *)indexPath{
    return 0;
}


//每一个cell
-(CustomTableCell *)customGridView:(CustomGridView *)customGridView cellAtIndexPath:(CustomIndexPath *)indexPath{
    
    static NSString *cellIdentifier =@"VideoPlayerVideoListCell";  //cellIdentifier同时也是自定义xib的名字。。
    CustomTableCell *cell= [self.customGridView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[CustomTableCell alloc] initWithIdentifier:cellIdentifier];
        
    }
    
    int index=indexPath.column+indexPath.row*NumsOfColumn;
    
    UIButton *btn=(UIButton *)[cell viewWithTag:201];
    [btn setTitle:[NSString stringWithFormat:@"%d",index+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[Common createImageWithColor:RGB(255, 121, 0)] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(cellCliked:) forControlEvents:UIControlEventTouchUpInside];
    
    //VideoObj* videoObj = [self.videoListArray objectAtIndex:index];
    
    //BOOL isHave=[[cur objectForKey:HttpEveryEpisodeHave] intValue];
    BOOL isHave = YES;
    btn.enabled=isHave;
    
    if (index == self.videoObj.currentPlayIndex) {
        btn.selected=YES;
    }else{
        btn.selected=NO;
    }
    
    return cell;
}

-(void)cellCliked:(id)sender{
    //统计
   
    UIButton *btn=(UIButton *)sender;
    int index=[[btn titleForState:UIControlStateNormal] integerValue]-1;
    
    if (index == self.videoObj.currentPlayIndex) {
        return;
    }

//    [self handleWhenGoBackWithPlayIndex:index andIsNeedToHandleTheVideoList:YES];

}

#pragma -mark first guide
-(void)firstGoToPlay{
    NSUserDefaults *userDefault= [NSUserDefaults standardUserDefaults];
    if (![userDefault objectForKey:FirstToPlayVideo]) {
        [self.view addSubview:self.firstRunView];
        if (!isPad && !isiPhone5) {
            self.firstRunView.left = - (568 - 480)/2;
        }
        
        UITapGestureRecognizer *tapGes=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideFirstRunWithKey)];
        [self.firstRunView addGestureRecognizer:tapGes];
    }
}

-(void)hideFirstRunWithKey{
    NSUserDefaults *userDefault= [NSUserDefaults standardUserDefaults];
    [userDefault setObject:FirstToPlayVideo forKey:FirstToPlayVideo];
    [userDefault synchronize];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.firstRunView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.firstRunView removeFromSuperview];
    }];
}


#pragma -mark baidu
-(void)viewWillAppear:(BOOL)animated
{
   
}

-(void)viewWillDisappear:(BOOL)animated
{

}

#pragma mark - 屏幕旋转
-(BOOL) shouldAutorotate {
	return YES;
}

-(NSUInteger) supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskLandscape;
}

#pragma mark - 状态栏的控制

//针对ios7的 导航栏处理，通过改变值，然后刷导航条，就会调用prefersStatusBarHidden这个函数，来让导航条是否可见，调用preferredStatusBarStyle来改变文字颜色
-(void)handleTheStateBarAnimationDur:(float) dur andDisplay:(BOOL)display{
    if (isiOS7) {
        self.stateBarDisplay=display;
        [UIView animateWithDuration:dur animations:^{
            [self setNeedsStatusBarAppearanceUpdate];
        }];
    }
}

//控制状态栏可见性
- (BOOL)prefersStatusBarHidden
{
    
    return !self.stateBarDisplay;
}

//状态栏文字颜色
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
